package controller;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;

import com.sun.jersey.api.client.Client; // Classes pour
import com.sun.jersey.api.client.WebResource; // traiter des
import com.sun.jersey.core.header.MediaTypes; // appels REST
import javax.ws.rs.core.MediaType; //
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; // Classes pour
import javax.xml.bind.JAXBContext; // la conversion
import javax.xml.bind.JAXBElement; // XML <-> Objet
import javax.xml.transform.stream.StreamSource;//
import java.io.StringReader; //
import java.lang.reflect.Array;

import view.User;

import data.Game;
import data.Player;

public class ServiceGameImpl implements ServiceGame, Runnable {
	private HashMap<Game,ArrayList<User>> listOfGame;
	private WebResource serviceGame;

	public ServiceGameImpl() {
		this.listOfGame 	= new HashMap<Game,ArrayList<User>>();
	}
	
	public boolean abonner(User p) throws RemoteException {
		return false;
	}
	
	public void desabonner(User p) throws RemoteException {

	}

	public boolean createAccount(String login) throws RemoteException {
		return true;
	}

	@Override
	public void run() {
		serviceGame= Client.create().resource("http://localhost:8080/bataille");

		while(true)	{
			try {

				
				Thread.sleep(3000) ;
			} catch (InterruptedException e) {}
		}
		
	}

	@Override
	public void createGame(User p,int nbPlayers) throws RemoteException {
		Game createGame=new Game();
		
		//get all the information for the new game from the web service
		//insert it into the hash map
		String response=serviceGame.path("/game/add/"+nbPlayers+"/"+0).get(String.class);
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Game.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			StringBuffer xmlStr = new StringBuffer(response);
			JAXBElement<Game> root = unmarshaller.unmarshal(new StreamSource(new StringReader(xmlStr.toString())),Game.class);
			createGame= root.getValue();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		listOfGame.put(createGame, new ArrayList<User>());
		listOfGame.get(createGame).add(p);
	}
	
}
